<!--
 * @Description: 填报总目标成本数据
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2024-03-01 18:32:49
 * @LastEditTime: 2024-04-03 11:37:49
 * @FilePath: \cscec-pms-admin\src\views\businessAffairs\businessCostPlanManagement\costPlanManagement\costPlan\components\InformationInit\components\FillingInData\index.vue
-->
<template>
  <div class="table-wrapper">
    <a-button type="primary" @click="handleExpand" style="margin-bottom: 10px"> 展示二级科目 </a-button>
    <u-table
      ref="table"
      fixed-columns-roll
      :height="height"
      show-header-overflow
      :tree-config="{
        children: 'children',
        expandAll: false
      }"
      row-id="id"
      :use-virtual="true"
      border
      :row-height="40"
    >
      <u-table-column
        v-for="item in columns"
        :key="item.dataIndex"
        :prop="item.dataIndex"
        :label="item.title"
        :width="item.width"
        :minWidth="item.minWidth"
        :fixed="item.fixed"
        :tree-node="item.dataIndex === 'name'"
        align="left"
      >
        <template v-slot="{ row }">
          <template v-if="item.dataIndex === 'targetAmount'">
            <BaseInputNumber v-if="row.isEditValue" v-model="row[item.dataIndex]" :precision="2" @blur="handleUpdate(row, item.dataIndex,'targetAmount')" />
            <p v-else :title="row[item.dataIndex]">{{ row[item.dataIndex] | setPlaceholder }}</p>
          </template>
          <template v-else-if="item.dataIndex === 'actualAmount'">
            <BaseInputNumber v-if="row.isEditAcValue" v-model="row[item.dataIndex]" :precision="2" @blur="handleUpdate(row, item.dataIndex,'actualAmount')" />
            <p v-else :title="row[item.dataIndex]">{{ row[item.dataIndex] |  setPlaceholder  }}</p>
          </template>
          <template v-else-if="item.dataIndex === 'startTime'">
            <a-month-picker
              v-if="(row.isEditTime || row.isDateEdit == 1 )&& isAddFn(row,item.dataIndex) "
              v-model="row[item.dataIndex]"
              :disabled-date="
                (current) => {
                  return startTimeDisabledDate(current, row)
                }
              "
              @change="handleUpdate(row, item.dataIndex)"
            />
            <p v-else :title="row[item.dataIndex]">{{ row[item.dataIndex] }}</p>
          </template>
          <template v-else-if="item.dataIndex === 'endTime'">
            <a-month-picker
              v-if="(row.isEditTime  || row.isDateEdit == 1) &&isAddFn(row,item.dataIndex)"
              v-model="row[item.dataIndex]"
              :disabled-date="
                (current) => {
                  return endTimeDisabledDate(current, row)
                }
              "
              @change="handleUpdate(row, item.dataIndex)"
            />
            <p v-else :title="row[item.dataIndex]">{{ row[item.dataIndex] }}</p>
          </template>
          <template v-else-if="item.dataIndex === 'description'">
            <BaseInput v-model="row[item.dataIndex]" @blur="handleUpdate(row, item.dataIndex)" />
          </template>
          <p v-else :title="row[item.dataIndex]">{{ row[item.dataIndex] | setPlaceholder }}</p>
        </template>
      </u-table-column>
    </u-table>
  </div>
</template>
<script>
import { UTable, UTableColumn } from 'umy-ui'
import { columns } from './model.js'
import moment from 'moment'
import { getCostPlan as queryPlan, editProjectTree } from '@/api/businessAffairs/costAccountInit'
import { publicMixin } from './../../../public'
import { placeholder } from '../../../../../../headquartersDashboard/components/placeholderWay.js'
export default {
  name: 'CostAccountInit',
  mixins: [publicMixin], //混入文件
  components: {
    UTable,
    UTableColumn
  },
  data() {
    return {
      // 表格高度
      height: 0,
      // 表格数据
      data: [],
      // 表格数据映射
      dataMap: new Map(),
      // 当前项目id
      projectId: this.$userInfo()?.currentPost?.projectId,
      // 开始时间
      startTime: ''
    }
  },
  computed: {
    // 表头
    columns() {
      return this.$clone(columns)
    }
  },
  mounted() {
    this.height = document.querySelector('.table-wrapper').offsetHeight - 42
    this.getTableData()
  },
  filters:{
    setPlaceholder(val){
      return placeholder(val)
    }
  },
  methods: {
    isAddFn(row,name){
      let arr =  false
      if(row.children.length > 0){
        row.children.forEach(item=>{
          arr = row.level == 2 && item.code.slice(-1) == 'T'  ? false : true
        })
      } else  {
        arr = true
      }
      return arr
    },
    /**
     * @description: 节点开始时间禁用规则
     * @param {object} current 当前时间对象
     * @param {object} row 行数据
     * @return {boolean}
     */
    startTimeDisabledDate(current, row) {
      const dayOfMonth = moment().format('DD');
      if (row.endTime) {
        return current && (current < moment(this.startTime).startOf('month') || current > moment(row.endTime).add(dayOfMonth*1, 'day'))
      } else {
        return current && current < moment(this.startTime).startOf('month')
      }
    },
    /**
     * @description: 节点考核时间禁用规则
     * @param {object} current 当前时间对象
     * @param {object} row 行数据
     * @return {boolean}
     */
    endTimeDisabledDate(current, row) {
      if (row.startTime) {
        return current && (current < moment(this.startTime).startOf('month') || current < moment(row.startTime))
      } else {
        return current && current < moment(this.startTime).startOf('month')
      }
    },
    /**
     * @description: 扁平化树
     * @param {array} tree 树
     * @return {void}
     */
    flattenTree(tree) {
      for (let i = 0; i < tree.length; i++) {
        this.dataMap.set(tree[i].id, tree[i])
        if (tree[i].isShow && tree[i]?.children?.length) {
          this.secondaryAccount.push(tree[i].id)
        }
        if (tree[i]?.children && tree[i].children?.length > 0) {
          this.flattenTree(tree[i].children)
        }
      }
    },
    /**
     * @description: 获取表格数据
     * @return {void}
     */
    getTableData(flag) {
      this.$emit('update:spinning', true)
      let req = {
        projectId: this.projectId,
        isHide: false,
        isShow: false
      }
      queryPlan(req)
        .then((res) => {
          if (res.code === '0') {
            this.data = res.data?.trees
            this.startTime = res.data?.startTime
            this.secondaryAccount = []
            this.reloadData(this.data)
          }
        })
        .finally(() => {
          this.$emit('update:spinning', false)
        })
    },
    //展开二级科目
    handleExpand() {
      this.secondaryAccount.forEach((el) => {
        this.$refs.table.setTreeExpansion(this.dataMap.get(el), true)
      })
      this.handleSubmit(0)
    },
    /**
     * @description: 加载数据
     * @param {array} data
     * @return {void}
     */
    reloadData(data) {
      this.flattenTree(data)
      // 获取之前展开数据
      const expandRecords = this.$refs.table.getTreeExpandRecords()
      // 获取之前滚动高度(表格实例上的scrollTop属性，在滚动到底部时会小于真实的scrollTop值，因此直接从dom获取真实滚动高度)
      const scrollTop = this.$refs.table.tableExample().bodyWrapper.scrollTop
      const scrollLeft = this.$refs.table.tableExample().bodyWrapper.scrollLeft
      // 加载数据
      this.$refs.table.reloadData(data).then(() => {
        // 数据加载完成出现之后，打开之前的展开行
        expandRecords.forEach((row) => {
          this.$refs.table.setTreeExpansion(row, true)
        })
        this.$refs.table.pagingScrollTopLeft(scrollTop, scrollLeft)
      })
    },
    /**
     * @description: 编辑
     * @param {object} row 行数据
     * @param {string} blurIndex 失焦字段
     * @return {void}
     */
    handleUpdate(row, blurIndex, key) {
      this.dataMap.get(row.id)[blurIndex] = row[blurIndex]?._isAMomentObject ? row[blurIndex].format('YYYY-MM') : row[blurIndex]
      if(blurIndex === 'startTime' || blurIndex === 'endTime'){
        this.dataMap.get(row.id).isDateEdit = 1
      }
      this.reloadData(this.data)
      if (key) {
        let changeTreeData = this.changeTreeData(this.data, row,key)
        this.reloadData(changeTreeData)
      }
    },
    /**
     * @description: 提交
     * @return {promise}
     */
    handleSubmit(step) {
      return new Promise((resolve, reject) => {
        this.$emit('update:spinning', true)
        const params = {
          trees: Array.from(this.$clone(this.dataMap).values()).map((el) => {
            delete el.children
            return el
          }),
          step: step
        }
        editProjectTree(params)
          .then((res) => {
            if (res.data.length === 0) {
              this.$emit('update:spinning', false)
              resolve()
            } else {
              this.$emit('update:spinning', false)
              reject(res.data)
            }
          })
          .catch((err) => {
            console.log(err)
            this.$emit('update:spinning', false)
            reject(err)
          })
      })
    }
  }
}
</script>
<style lang="less" scoped></style>
